<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>{{ isEdit ? '编辑预订信息' : '创建场馆预订' }}</span>
        </div>
      </template>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" :key="formKey">
        <!-- 基础信息 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="活动标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入活动标题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="组织者" prop="organizer_id">
              <el-select
                v-model="form.organizer_id"
                placeholder="请输入关键词搜索组织者"
                filterable
                remote
                :remote-method="handleSearchUsers"
                :loading="userSearchLoading"
                style="width: 100%;"
                no-data-text="未找到用户"
                no-match-text="未找到用户"
              >
                <el-option
                  v-for="item in userOptions"
                  :key="item.id"
                  :label="`${item.nickname}${item.phone ? ` (${item.phone})` : ''}`"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 场馆和时间选择 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="场馆" prop="venue_id">
              <el-select
                v-model="form.venue_id"
                placeholder="请选择场馆"
                :disabled="!!venueIdFromRoute"
                style="width: 100%;"
                @change="handleVenueChange"
              >
                <el-option
                  v-for="venue in venueOptions"
                  :key="venue.id"
                  :label="venue.name"
                  :value="venue.id.toString()"
                />
              </el-select>
              <div v-if="venueIdFromRoute" class="venue-tip">
                <el-text type="info" size="small">场馆已从列表页面选择，不可修改</el-text>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预订日期" prop="booking_date">
              <el-date-picker
                v-model="bookingDate"
                type="date"
                placeholder="请选择预订日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%;"
                @change="onDateTimeChange"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startHour">
              <el-time-select
                v-model="startHour"
                start="00:00"
                step="01:00"
                end="23:00"
                placeholder="请选择开始时间"
                style="width: 100%"
                @change="onDateTimeChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="endHour">
              <el-time-select
                v-model="endHour"
                :min-time="startHour"
                start="01:00"
                step="01:00"
                end="24:00"
                placeholder="请选择结束时间"
                style="width: 100%"
                @change="onDateTimeChange"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="可用性检查">
          <el-tag :type="venueAvailable ? 'success' : 'danger'">
            {{ venueAvailabilityMessage }}
          </el-tag>
        </el-form-item>

        <!-- 其他信息 -->
        <el-form-item label="活动描述" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="4" placeholder="请输入活动描述" />
        </el-form-item>
        <el-form-item label="活动海报" prop="poster_url">
          <UploadImage v-model="form.poster_url" />
        </el-form-item>
        <el-form-item label="人数限制" prop="participants_limit">
          <el-input-number v-model="form.participants_limit" :min="1" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="2">草稿</el-radio>
            <el-radio :label="0">已取消</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">{{ isEdit ? '更新' : '创建' }}</el-button>
          <el-button @click="router.back()">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { ref, onMounted, computed, watch, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getActivityDetail, createActivity, updateActivity } from '@/api/activity'
import { venueApi } from '@/api/venue'
import { searchUsers } from '@/api/user'
import UploadImage from '@/components/UploadImage/index.vue'
import { format, parseISO } from 'date-fns'

export default {
  name: 'VenueBooking',
  components: { UploadImage },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const formRef = ref(null)

    // --- State Management ---
    const isEdit = ref(false)
    const userSearchLoading = ref(false)
    
    const initialFormState = {
      title: '',
      description: '',
      poster_url: '',
      organizer_id: '',
      venue_id: '',
      start_time: '',
      end_time: '',
      venue_start_time: '',
      venue_end_time: '',
      participants_limit: 1,
      status: 1,
      booking_type: 1
    }

    const form = ref({ ...initialFormState })
    const bookingDate = ref('')
    const startHour = ref('')
    const endHour = ref('')

    const venueOptions = ref([])
    const userOptions = ref([])
    const venueAvailable = ref(false)
    const venueAvailabilityMessage = ref('请选择场馆和时间以检查可用性')

    const venueIdFromRoute = computed(() => {
      return route.query.createForVenue === 'true' ? route.params.id : null
    })

    const rules = {
      title: [{ required: true, message: '请输入活动标题', trigger: 'blur' }],
      organizer_id: [{ required: true, message: '请选择组织者', trigger: 'change' }],
      venue_id: [{ required: true, message: '请选择场馆', trigger: 'change' }],
      bookingDate: [{ required: true, message: '请选择预订日期', trigger: 'change' }],
      startHour: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
      endHour: [{ required: true, message: '请选择结束时间', trigger: 'change' }]
    }
    
    // --- Core Functions ---
    const resetForm = () => {
      form.value = { ...initialFormState }
      bookingDate.value = ''
      startHour.value = ''
      endHour.value = ''
      userOptions.value = []
      if (formRef.value) {
        formRef.value.clearValidate()
      }
    }

    const combineDateTime = () => {
      if (bookingDate.value && startHour.value && endHour.value) {
        const startTimeStr = `${bookingDate.value} ${startHour.value}:00`
        const endTimeStr = `${bookingDate.value} ${endHour.value}:00`
        form.value.start_time = startTimeStr
        form.value.end_time = endTimeStr
        form.value.venue_start_time = startTimeStr
        form.value.venue_end_time = endTimeStr
        return true
      }
      return false
    }

    const checkVenueAvailability = async () => {
      if (!form.value.venue_id || !combineDateTime()) {
        return
      }

      try {
        const response = await venueApi.checkAvailability(
          form.value.venue_id,
          form.value.venue_start_time,
          form.value.venue_end_time
        )

        if (response.code === 200) {
          const data = response.data
          venueAvailable.value = data.available
          if (data.available) {
            venueAvailabilityMessage.value = '该时间段可用'
          } else {
            const conflictMsg = data.conflicting_activities?.[0]?.title
            venueAvailabilityMessage.value = conflictMsg 
              ? `该时间段与活动【${conflictMsg}】冲突` 
              : '该时间段不可用或已被预订'
          }
        } else {
          venueAvailable.value = false
          venueAvailabilityMessage.value = response.message || '检查可用性失败'
        }
      } catch (error) {
        console.error('检查场馆可用性失败:', error)
        venueAvailable.value = false
        const errorMessage = error.response?.data?.message || error.message || '网络错误'
        venueAvailabilityMessage.value = `检查失败: ${errorMessage}`
      }
    }

    const onDateTimeChange = () => {
      checkVenueAvailability()
    }

    const loadAllVenues = async () => {
      try {
        const response = await venueApi.getList({ perPage: 1000 })
        venueOptions.value = response.data.venues || []
      } catch (error) {
        console.error('加载所有场馆列表失败:', error)
      }
    }

    const handleSearchUsers = async (query) => {
      userSearchLoading.value = true
      try {
        const response = await searchUsers({ keyword: query || '' })
        const newOptions = response.data.users || []

        const selectedUserId = form.value.organizer_id
        if (selectedUserId) {
          const isSelectedInNew = newOptions.some(u => u.id === selectedUserId)
          if (!isSelectedInNew) {
            const currentSelected = userOptions.value.find(u => u.id === selectedUserId)
            if (currentSelected) {
              newOptions.unshift(currentSelected)
            }
          }
        }
        userOptions.value = newOptions
      } catch (error) {
        console.error('搜索用户失败:', error)
        userOptions.value = []
      } finally {
        userSearchLoading.value = false
      }
    }

    const loadBookingInfo = async (id) => {
      try {
        const response = await getActivityDetail(id)
        if (response.code === 200) {
          const data = response.data
          form.value = { ...data, id: data.id, venue_id: data.venue_id?.toString() }
          
          if (data.organizer) {
            userOptions.value = [data.organizer]
          }
          
          if (data.start_time) {
            bookingDate.value = format(parseISO(data.start_time), 'yyyy-MM-dd')
            startHour.value = format(parseISO(data.start_time), 'HH:mm')
          }
          if (data.end_time) {
            endHour.value = format(parseISO(data.end_time), 'HH:mm')
          }

          await nextTick()
          checkVenueAvailability()
          return true
        }
        return false
      } catch (error) {
        console.error('加载预订信息失败:', error)
        return false
      }
    }

    const handleVenueChange = () => {
        onDateTimeChange();
    }
    
    onMounted(async () => {
      resetForm()
      await loadAllVenues()
      
      const entityId = route.params.id
      const isCreatingForVenue = route.query.createForVenue === 'true'

      if (isCreatingForVenue && entityId) {
        isEdit.value = false
        form.value.venue_id = entityId.toString()
      } else if (entityId) {
        isEdit.value = true
        const success = await loadBookingInfo(entityId)
        if (!success) {
          ElMessage.error('加载预订信息失败，请返回重试')
          router.back()
        }
      } else {
        isEdit.value = false
      }
      
      // 预加载用户列表以显示默认组织者
      if (!isEdit.value && !userOptions.value.length) {
          handleSearchUsers('')
      }
    })

    const handleSubmit = () => {
      formRef.value.validate(async (valid) => {
        if (valid) {
          if (!combineDateTime()) {
            ElMessage.error('请确保已选择完整的日期和时间')
            return
          }

          try {
            let response
            if (isEdit.value) {
              response = await updateActivity(form.value.id, form.value)
            } else {
              response = await createActivity(form.value)
            }

            if (response.code === 200) {
              ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
              router.back()
            } else {
              ElMessage.error(response.message || '操作失败')
            }
          } catch (error) {
            console.error('提交失败:', error)
            ElMessage.error('提交失败')
          }
        }
      })
    }
    
    return {
      formRef,
      form,
      rules,
      isEdit,
      bookingDate,
      startHour,
      endHour,
      venueOptions,
      userOptions,
      userSearchLoading,
      venueAvailable,
      venueAvailabilityMessage,
      venueIdFromRoute,
      handleSearchUsers,
      handleVenueChange,
      onDateTimeChange,
      handleSubmit,
      router,
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.venue-tip {
  margin-top: 8px;
  padding: 8px 12px;
  background-color: #f0f9ff;
  border: 1px solid #b3d8ff;
  border-radius: 4px;
}
</style>

